export function validateCreditCode(value, callback) {
	const reg = /^[^_IOZSVa-z\W]{2}\d{6}[^_IOZSVa-z\W]{10}$/
	if (!reg.test(value)) {

		callback('error')
	}
}

export const checkPositiveIntegers = (num, error_msg) => {
	let bool = false;
	const r = /^\+?[0-9]*$/; //正整数
	if (!r.test(num)) {
		toast(error_msg)
		bool = true;
	};
	return bool
}
/**
 * 显示消息提示框
 * @param { String } title 提示的内容，长度与 icon 取值有关。
 * @param { String } position 纯文本轻提示显示位置top,center,bottom
 * @param { String } icon 图标，有效值详见uniapp官方说明。success，error，fail，exception，loading，none
 * @param { Number } duration 提示的延迟时间，单位毫秒，默认：1500
 * @param { Boolean } mask 防止触摸穿透
 * @example this.$utils.toast(title);
 */
export function toast(title, icon = 'none', duration = 2000, position = 'center', mask = false) {
	uni.showToast({
		title,
		position,
		icon,
		duration,
		mask
	});
}
export function addZero(str) {
	return parseInt(str) < 10 ? '0' + str : str;
}
export function formatDuring(mss) {
	var days = parseInt(mss / (1000 * 60 * 60 * 24));
	var hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
	var minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
	var seconds = parseInt((mss % (1000 * 60)) / 1000);
	let str = '';
	if (days > 0) {
		str += days + " 天 ";
	}
	if (hours > 0) {
		str += hours + " 小时 ";
	}
	if (minutes > 0) {
		str += minutes + " 分钟 ";
	}
	if (seconds > 0) {
		str += seconds + " 秒 ";
	}
	return str;
}
/**
 * 获取当前时间
 */
export function getNowTime() {
	var date = new Date(),
		year = date.getFullYear(),
		month = date.getMonth() + 1,
		day = date.getDate(),
		hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(),
		minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(),
		second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
	month >= 1 && month <= 9 ? (month = "0" + month) : "";
	day >= 0 && day <= 9 ? (day = "0" + day) : "";
	return (year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second);
}
//日期转换字符串
export function formatDateStr(date) {
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()
	const hour = date.getHours()
	const minute = date.getMinutes()
	const second = date.getSeconds();
	const ymd = [year, month, day].map(formatNum).join('-');
	const hms = [hour, minute, second].map(formatNum).join(':')
	return ymd + ' ' + hms
}
//格式化日期转换字符串
export function getDateStr(date) {
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()
	const hour = date.getHours()
	const minute = date.getMinutes()
	const second = date.getSeconds();
	const ymd = [year, month, day].map(formatNum).join('');
	const hms = [hour, minute, second].map(formatNum).join('')
	return ymd +  hms
}
export function formatNum(num) {
	return num >= 10 ? num : '0' + num;
}
/**
 * @param {date} time 需要转换的时间
 * @param {String} fmt 需要转换的格式 如 yyyy-MM-dd、yyyy-MM-dd HH:mm:ss
 */
export function formatTime(time, fmt) {
	if (!time) return '';
	else {
		const date = new Date(time);
		const o = {
			'M+': date.getMonth() + 1,
			'd+': date.getDate(),
			'H+': date.getHours(),
			'm+': date.getMinutes(),
			's+': date.getSeconds(),
			'q+': Math.floor((date.getMonth() + 3) / 3),
			S: date.getMilliseconds(),
		};
		if (/(y+)/.test(fmt))
			fmt = fmt.replace(
				RegExp.$1,
				(date.getFullYear() + '').substr(4 - RegExp.$1.length)
			);
		for (const k in o) {
			if (new RegExp('(' + k + ')').test(fmt)) {
				fmt = fmt.replace(
					RegExp.$1,
					RegExp.$1.length === 1 ?
					o[k] :
					('00' + o[k]).substr(('' + o[k]).length)
				);
			}
		}
		return fmt;
	}
}
export function getNameByType(arr, type) {
	if (!arr) return '';
	const filters = arr.filter(item => {
		return item.value.toString() == type.toString()
	});
	if (filters.length > 0) {
		return filters[0].label;
	}
}
// 星期格式转换 0-6：周日到周六
export function weekFormat(e, prefix = "周") {
	switch (e) {
		case 0:
			return prefix + "日"
			break;
		case 1:
			return prefix + "一"
			break;
		case 2:
			return prefix + "二"
			break;
		case 3:
			return prefix + "三"
			break;
		case 4:
			return prefix + "四"
			break;
		case 5:
			return prefix + "五"
			break;
		case 6:
			return prefix + "六"
			break;
		default:
			return ""
			break;
	}
}
// 是否显示周几
export function isShowWeekDay(sub, weekDay) {
	const currentWeekDay = new Date().getDay()
	const dayTime = 1000 * 60 * 60 * 24
	// 1.当前时间与消息时间相差必须大于2天小于7天
	// 2.当前时间距离本周一相差必须大于2天且小于当前距离周一的天数
	// 3.消息时间不可能是0-周日，因为周日没有给后面时间留空间，不会走这里的逻辑，而是走今天的逻辑
	if (sub >= dayTime * 2 && weekDay !== 0 && sub <= dayTime * currentWeekDay) {
		return true
	} else {
		return false
	}
}
//获取位置信息
export function getLocation() {
	return new Promise((res, rej) => {
		uni.getLocation({
			type: "wgs84",
			geocode: true, //必写项
			success: (data) => {
				res(data);
			},
			fail: (rej) => {
				rej(rej)
			}
		});
	});
}
export function Rad(d) {
	//根据经纬度判断距离
	return d * Math.PI / 180.0;
}
//计算两点之间的距离 返回的距离是公里km
export function getDistance(lat1, lng1, lat2, lng2) {
	// lat1用户的纬度
	// lng1用户的经度
	// lat2商家的纬度
	// lng2商家的经度
	var radLat1 = Rad(lat1);
	var radLat2 = Rad(lat2);
	var a = radLat1 - radLat2;
	var b = Rad(lng1) - Rad(lng2);
	var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math
		.sin(b / 2), 2)));
	s = s * 6378.137;
	s = Math.round(s * 10000) / 10000;
	s = s.toFixed(1) //保留两位小数
	console.log('经纬度计算的距离:' + s)
	return s
}
// 解析链接中的参数
export function getQueryString(url, name) {
	console.log("url = " + url)
	console.log("name = " + name)
	var reg = new RegExp('(^|&|/?)' + name + '=([^&|/?]*)(&|/?|$)', 'i')
	var r = url.substr(1).match(reg)
	if (r != null) {
		// console.log("r = " + r)
		// console.log("r[2] = " + r[2])
		return r[2]
	}
	return null;
}
//16进制转字符串
export function hexToString(str) {
	var trimedStr = str.trim();
	var rawStr =
		trimedStr.substr(0, 2).toLowerCase() === "0x" ?
		trimedStr.substr(2) :
		trimedStr;
	var len = rawStr.length;
	if (len % 2 !== 0) {
		// alert("Illegal Format ASCII Code!");
		return "";
	}
	var curCharCode;
	var resultStr = [];
	for (var i = 0; i < len; i = i + 2) {
		curCharCode = parseInt(rawStr.substr(i, 2), 16); // ASCII Code Value
		resultStr.push(String.fromCharCode(curCharCode));
	}
	return resultStr.join("");
}

// ArrayBuffer转16进制字符串示例
export function ab2hext(buffer) {
	var hexArr = Array.prototype.map.call(
		new Uint8Array(buffer),
		function(bit) {
			return ('00' + bit.toString(16)).slice(-2)
		}
	)
	return hexArr.join('');
}
// 字符串转byte
export function stringToBytes(str) {
	var strArray = new Uint8Array(str.length);
	for (var i = 0; i < str.length; i++) {
		strArray[i] = str.charCodeAt(i);
	}
	const array = new Uint8Array(strArray.length)
	strArray.forEach((item, index) => array[index] = item)
	return array.buffer;
}
//string: suffix_name 后缀名
export function fileName(path, suffix_name) {
	let date = new Date;
	let year = date.getFullYear();
	let month = date.getMonth() + 1;
	// 保存路径
	var _fileName = path + year + "-" + month + "/" + Date.parse(new Date()) +
		parseInt(
			Math.random() * (100000 - 10000 + 1) + 10000, 10) + "." + suffix_name;
	return _fileName;
}


/**
 * @param {Object} imgUrl,图片地址,
 * severUrl 服务器地址
 */
export function uploadImg(imgUrl, severUrl, callBack) {

	uni.showLoading({
		title: '图片上传中...'
	});
	uni.uploadFile({
		url: severUrl, //从调用页面传入 -- url: 'http://127.0.0.1:3000/' 后端接口地址
		filePath: imgUrl, //从调用页面传入 --path: imgbox, 选取图片的地址数组  
		name: 'file', //文件名称可以自定义，要与后端配对使用：app.post('/',upload.single('img'),function(req,res,next)
		success: (resp) => {
			//图片上传成功，图片上传成功的变量+1
			const data = JSON.parse(resp.data);
			callBack(data.data.url);
			uni.hideLoading();
			console.log(resp.data) //在调试窗口显示后端返回的图片名称      
		},
		fail: (fail) => { //失败
			uni.hideLoading();
			toast('上传失败', 'error')
			console.log('fail:', fail);
		},
		complete: (e) => { //不论成功、失败都执行		
			uni.hideLoading();
			console.log('执行完毕');
		}
	});
}
export function maskPhoneNumber(phoneNumber) {
	if (!phoneNumber) return ''
	return phoneNumber.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
}
export function isValidIdNumber(idNumber) {
	// 简单的身份证号码验证规则
	const pattern = /^[1-9]\d{5}(18|19|20|21|22)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|[Xx])$/;
	return pattern.test(idNumber);
}
export function isValidPhone(phone) {

	let reg = /^((13[0-9])|(14[0-9])|(16[0-9])|(15[0-9])|(17[0-9])|(19[0-9])|(18[0-9]))\d{8}$/;

	return reg.test(phone)

}
export function openSetting(str1, str2) {
	wx.showModal({
		title: '提示', //提示的标题,
		content: str1, //提示的内容,
		showCancel: true, //是否显示取消按钮,
		cancelText: '取消',
		confirmText: '确定',
		success: (res) => {
			if (res.confirm) {
				wx.openSetting({
					success(res) {

						console.log(res)
					},
					fail(res) {}
				})
			} else if (res.cancel) {
				console.log('用户点击取消')
				wx.showToast({
					title: str2,
					icon: 'none',
					duration: 2000,
				})
			}
		}
	});
}
//utils.js
 
export function getDate(date, AddDayCount = 0) {
  if (!date) {
    date = new Date()
  }
  if (typeof date !== 'object'){
    date = date.replace(/-/g, '/')
  }
  const dd = new Date(date)
  dd.setDate(dd.getDate() + AddDayCount) // 获取AddDayCount天后的日期
  const y = dd.getFullYear()
  const m = dd.getMonth() + 1 < 10 ? '0' + (dd.getMonth() + 1) : dd.getMonth() + 1 // 获取当前月份的日期，不足10补0
  const d = dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate() // 获取当前几号，不足10补0
  return {
    fullDate: y + '-' + m + '-' + d,
    year: y,
    month: m,
    date: d,
    day: dd.getDay()
  }
}
export function debounce(fn, delay) {
  let timer = null;
  return function() {
    let context = this;
    let args = arguments;
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(context, args);
    }, delay);
  };
}